package com.google.code.sms.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.mvc.SimpleFormController;

import com.google.code.sms.command.GeneralSettingsCommand;
import com.google.code.sms.service.SettingsService;

/**
 * Controller for the page used to administrate general settings.
 *
 * @author Sindre Mehus
 */
public class GeneralSettingsController extends SimpleFormController {

    private SettingsService settingsService;

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        GeneralSettingsCommand command = new GeneralSettingsCommand();
        command.setCoverArtFileTypes(settingsService.getCoverArtFileTypes());
        command.setPosterFileTypes(settingsService.getPosterFileTypes());
        command.setSubtitlesFileTypes(settingsService.getSubtitlesFileTypes());
        command.setIgnoredArticles(settingsService.getIgnoredArticles());
        command.setIndex(settingsService.getIndexString());
        command.setPlaylistFolder(settingsService.getPlaylistFolder());
        command.setMusicFileTypes(settingsService.getMusicFileTypes());
        command.setVideoFileTypes(settingsService.getVideoFileTypes());

        return command;

    }

    @Override
    protected void doSubmitAction(Object comm) throws Exception {
        GeneralSettingsCommand command = (GeneralSettingsCommand) comm;

        command.setToast(true);
        command.setReloadNeeded(!settingsService.getIndexString().equals(command.getIndex())
                || !settingsService.getIgnoredArticles().equals(command.getIgnoredArticles()));

        settingsService.setIndexString(command.getIndex());
        settingsService.setIgnoredArticles(command.getIgnoredArticles());
        settingsService.setPlaylistFolder(command.getPlaylistFolder());
        settingsService.setMusicFileTypes(command.getMusicFileTypes());
        settingsService.setVideoFileTypes(command.getVideoFileTypes());
        settingsService.setCoverArtFileTypes(command.getCoverArtFileTypes());
        settingsService.setPosterFileTypes(command.getPosterFileTypes());
        settingsService.setSubtitlesFileTypes(command.getSubtitlesFileTypes());
        settingsService.save();
    }

    public void setSettingsService(SettingsService settingsService) {
        this.settingsService = settingsService;
    }
}
